from django.conf import settings
from django.shortcuts import render
from rest_framework import status
from rest_framework.views import APIView
from QQLoginTool.QQtool import OAuthQQ
from rest_framework.response import Response
from rest_framework.generics import GenericAPIView, CreateAPIView
import requests

from carts.utils import merge_cart_cookie_to_redis
from oauth.models import OAuthQQUser
from rest_framework_jwt.settings import api_settings

from itsdangerous import TimedJSONWebSignatureSerializer as TJS



# Create your views here.
from oauth.serializers import OAuthQQSerializer


class OAuthQQURLView(APIView):
    def get(self, request):
        # 接受前端传递state
        state = request.query_params.get('state')
        if not state:
            state = '/'
        # 构建url 通过工具来实现
        print(settings.BASE_DIR)
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state=state)

        url = oauth.get_qq_url()

        # 返回url
        return Response(
            {'login_url': url}
        )

        # 使用QQ后跳转到http://www.meiduo.site:8080/oauth_callback.html?code=54877C25F35F54F09546D549995DB70F&state=%3Cbuilt-in%2Bfunction%2Bnext%3E


class OAuthQQView(CreateAPIView):

    # 指定序列化器
    serializer_class = OAuthQQSerializer

    def get(self, request):
        # 1.获取code
        code = request.query_params.get('code')
        if not code:
            return Response({'message': '缺少code值'}, status=status.HTTP_401_UNAUTHORIZED)

        # 2.通过code获取access_token
        # # 方法一:如果没有获取的现成方法使用requests模块获取
        # res = requests.get('https://graph.qq.com/oauth2.0/token',
        #                    params={'grant_type': 'authorization_code', 'client_id': settings.QQ_CLIENT_ID,
        #                            'client_secret': settings.QQ_CLIENT_SECRET, 'code': code,
        #                            'redirect_uri': settings.QQ_REDIRECT_URI})
        # data = res.text
        # # 方法二:使用现成封装好的方法
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET, redirect_uri=settings.QQ_REDIRECT_URI, state=next)
        access_token = oauth.get_access_token(code)

        # 3.通过access_token获取openid
        openid = oauth.get_open_id(access_token)

        # 4.判断openid是否绑定
        try:
            qq_user = OAuthQQUser.objects.get(openid=openid)
        except:
            # 未绑定过
            # openid加密
            tjs = TJS(settings.SECRET_KEY, 300)
            token = tjs.dumps({'openid': openid}).decode()

            return Response({'access_token':token})

        # 绑定过openid
        user = qq_user.user

        # 生成token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        response = Response(
            {
                'username':user.username,
                'user_id':user.id,
                'token':token
            }
        )

        # 合并购物车
        response = merge_cart_cookie_to_redis(request, user, response)

        return response

    # 要合并购物车,需要重写post方法
    def post(self, request, *args, **kwargs):
        response = super().post(request, *args, **kwargs)

        # 合并购物车
        response = merge_cart_cookie_to_redis(request, self.user, response)
        return response



